package com.ohuang.jiaxiaotong.Activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myhttp.CallBackObjects;
import com.example.myhttp.Ihttp;
import com.google.gson.Gson;
import com.ohuang.jiaxiaotong.Adapter.ChatRvAdapter;
import com.ohuang.jiaxiaotong.MainActivity;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.EventMsgCode;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.Util.SoftKeyBoardListener;
import com.ohuang.jiaxiaotong.Util.Sys;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.ChatMsg;
import com.ohuang.jiaxiaotong.entity.EventMsg;
import com.ohuang.jiaxiaotong.entity.User;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;

public class ChatActivity extends BaseAc {
    private String OtherUsername;
    private User user;
    private Button button_send;
    private RecyclerView recyclerView;
    private EditText editText_msg;
    private ArrayList<ChatMsg> mData;
    private ChatRvAdapter chatRvAdapter;
    private String content;
    private static final int RE_SUCCESS = 0, RE_FAIL = 1, RE_ERROR = 2, RE_OTHER = 3;
    private Dialog dialogLoading;
    private LinearLayoutManager linearLayoutManager;
    private boolean isConnect = true;//保持服务器通信
    SoftKeyBoardListener softKeyBoardListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        Intent intent = getIntent();
        EventBus.getDefault().register(this);
        OtherUsername = intent.getStringExtra("username");
        setTitle(OtherUsername);
        Ohuang.changeStatusBarTextImgColor(this, true);
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.mipmap.icon_goback);//设置ActionBar返回按钮
        initView();
        if (user != null) {
            HttpGetAllChatMsg();//获取数据
            connectServer.start();
        }
    }

    private void initView() {
        button_send = findViewById(R.id.btn_send_chat);
        recyclerView = findViewById(R.id.rv_chat);
        editText_msg = findViewById(R.id.edit_Msg_chat);
        button_send.setEnabled(false);
        editText_msg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int a = editText_msg.length();
                if (a < 1) {
                    button_send.setEnabled(false);
                } else {
                    button_send.setEnabled(true);
                }
            }
        });

        button_send.setOnClickListener(v -> {
            if (Sys.isClick()) {
                content = editText_msg.getText().toString();
                dialogLoading = Ohuang.dialogLoadingshow(ChatActivity.this, "发送中");
                httpSendMsg();//发送信息
            }
        });

        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        mData = new ArrayList<>();
        if (user != null) {
            chatRvAdapter = new ChatRvAdapter(this, mData, user.getUsername());
            recyclerView.setAdapter(chatRvAdapter);
        }

        softKeyBoardListener = new SoftKeyBoardListener(ChatActivity.this);
        softKeyBoardListener.setListener(ChatActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                Sys.MoveToPosition(linearLayoutManager, recyclerView, mData.size()-1);
            }

            @Override
            public void keyBoardHide(int height) {
                Sys.MoveToPosition(linearLayoutManager, recyclerView, mData.size() - 1);
            }
        });

    }

    Thread connectServer = new Thread(new Runnable() {
        @Override
        public void run() {
            while (isConnect) {
                try {
                    Thread.sleep(2000);
                    HttpAddNewChatMsg2();//刷新
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    //获取所有消息
    private void HttpGetAllChatMsg() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("sendName", user.getUsername());
        map.put("receiveName", OtherUsername);
        map.put("times", 0 + "");

        service.getChatMsg(map).enqueue(new retrofit2.Callback<ArrayList<ChatMsg>>() {
            @Override
            public void onResponse(retrofit2.Call<ArrayList<ChatMsg>> call, retrofit2.Response<ArrayList<ChatMsg>> response) {
                mData = response.body();
                chatRvAdapter.setmData(mData);
                chatRvAdapter.notifyDataSetChanged();
//                linearLayoutManager.setStackFromEnd(true);

                Sys.MoveToPosition(linearLayoutManager, recyclerView, mData.size() - 1);


            }

            @Override
            public void onFailure(retrofit2.Call<ArrayList<ChatMsg>> call, Throwable t) {

            }
        });
    }

    //发送后 刷新新的信息
    private void HttpAddNewChatMsg() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        double aa;
        if (mData == null) {
            aa = 0;
        } else if (mData.size() == 0) {
            aa = 0;
        } else {
            aa = mData.get(mData.size() - 1).getTimes();
        }
        map.put("sendName", user.getUsername());
        map.put("receiveName", OtherUsername);
        map.put("times", aa + "");

        service.getChatMsg(map).enqueue(new retrofit2.Callback<ArrayList<ChatMsg>>() {
            @Override
            public void onResponse(retrofit2.Call<ArrayList<ChatMsg>> call, retrofit2.Response<ArrayList<ChatMsg>> response) {
                ArrayList<ChatMsg> chatMsgs = response.body();
                if (chatMsgs.size() == 0) {
                    return;
                }
                for (ChatMsg chatMsg : chatMsgs) {
                    mData.add(chatMsg);
                }
                EventBus.getDefault().post(new EventMsg(EventMsgCode.CODE_6, "通知需要更新了"));
                chatRvAdapter.setmData(mData);
                chatRvAdapter.notifyDataSetChanged();
//                linearLayoutManager.setStackFromEnd(true);
                Sys.MoveToPosition(linearLayoutManager, recyclerView, mData.size() - 1);


            }

            @Override
            public void onFailure(retrofit2.Call<ArrayList<ChatMsg>> call, Throwable t) {

            }
        });
    }

    //刷新新的数据
    private void HttpAddNewChatMsg2() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        double aa;
        if (mData == null) {
            aa = 0;
        } else if (mData.size() == 0) {
            aa = 0;
        } else {
            aa = mData.get(mData.size() - 1).getTimes();
        }
        map.put("sendName", user.getUsername());
        map.put("receiveName", OtherUsername);
        map.put("times", aa + "");


        service.getChatMsg(map).enqueue(new retrofit2.Callback<ArrayList<ChatMsg>>() {
            @Override
            public void onResponse(retrofit2.Call<ArrayList<ChatMsg>> call, retrofit2.Response<ArrayList<ChatMsg>> response) {
                ArrayList<ChatMsg> chatMsgs = response.body();
                if (chatMsgs.size() == 0) {
                    return;
                }
                EventBus.getDefault().post(new EventMsg(EventMsgCode.CODE_6, "通知需要更新了"));
                for (ChatMsg chatMsg : chatMsgs) {
                    mData.add(chatMsg);
                }
                chatRvAdapter.setmData(mData);
                chatRvAdapter.notifyDataSetChanged();
//                linearLayoutManager.setStackFromEnd(true);
                Sys.MoveToPosition(linearLayoutManager, recyclerView, mData.size() - 1);


            }

            @Override
            public void onFailure(retrofit2.Call<ArrayList<ChatMsg>> call, Throwable t) {

            }
        });
    }

    //发送信息
    private void httpSendMsg() {
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("sendName", user.getUsername())
                .add("receiveName", OtherUsername)
                .add("content", content)
                .build();

        final Request request = new Request.Builder()
                .url(MyHttpURL.mainUrl + "chat/sendMsg")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                myHandler.sendEmptyMessage(RE_ERROR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                ResponseBody body = response.body();
                if (body != null) {
                    String code = body.string();
                    if ("success".equals(code)) {
                        myHandler.sendEmptyMessage(RE_SUCCESS);
                    } else if ("error".equals(code)) {
                        myHandler.sendEmptyMessage(RE_FAIL);
                    } else {
                        myHandler.sendEmptyMessage(RE_OTHER);
                    }
                    body.close();
                }
            }
        });
    }
    WebSocket mWebSocket;
    WebSocketListener webSocketListener=new WebSocketListener(){
        @Override
        public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
            super.onOpen(webSocket, response);
            mWebSocket=webSocket;
        }

        @Override
        public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
            super.onMessage(webSocket, text);
            ChatActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Gson gson=new Gson();
                    ChatMsg chatMsg=gson.fromJson(text,ChatMsg.class);
                    mData.add(chatMsg);
                    chatRvAdapter.notifyDataSetChanged();
                }
            });
        }
    };


    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case RE_SUCCESS:
                    dialogLoading.dismiss();
                    HttpAddNewChatMsg();//发送成功刷新
                    editText_msg.setText("");//文本去空
                    break;
                default:
                    dialogLoading.dismiss();
                    Toast.makeText(ChatActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };


    interface GithubService {
        @POST("chat/findMsg2")
        retrofit2.Call<ArrayList<ChatMsg>> getChatMsg(@QueryMap HashMap<String, String> deviceInfo);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetUserEventBus(User user) {
        this.user = user;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {//左上角返回按钮
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        isConnect = false;
    }

}
